package palmtop.com.palmtop.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import net.grandcentrix.tray.AppPreferences;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.lang.reflect.Type;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import palmtop.com.palmtop.R;
import palmtop.com.palmtop.model.RoleMenu;
import palmtop.com.palmtop.model.RoleUser;
import palmtop.com.palmtop.model.User;
import palmtop.com.palmtop.thread.NotificationThread;
import palmtop.com.palmtop.thread.PersonposThread;
import palmtop.com.palmtop.util.Config;
import palmtop.com.palmtop.util.NetUtil;
import palmtop.com.palmtop.util.ToastUtil;

public class LoginActivity extends AppCompatActivity {


    @BindView(R.id.login_account_input_layout)
    TextInputLayout loginAccountInputLayout;
    @BindView(R.id.login_password_input_layout)
    TextInputLayout loginPasswordInputLayout;
    /*@BindView(R.id.remeberMe)
    CheckBox remeberMe;*/

    @BindView(R.id.loginBtns)
    Button loginBtn;
    @BindView(R.id.login_name)
    EditText loginName;
    @BindView(R.id.password)
    EditText password;

    MyApplication app;
    private ArrayList<RoleMenu> arrayList;
    String permission;
//    SharedPreferences sharedPreferences;
//    SharedPreferences permissionSharedPermission;
    String usernameText;
    String nicknameText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        app = (MyApplication) getApplication();
        app.addActivity(LoginActivity.this);
        app.addActivityList(LoginActivity.this);
        arrayList = new ArrayList<RoleMenu>();
        AppPreferences appPreferences = new AppPreferences(LoginActivity.this);
//        appPreferences.clear();
        usernameText = appPreferences.getString("loginname", "0");
        nicknameText = appPreferences.getString("name", "0");

        if (usernameText != null && !usernameText.equals("0") && nicknameText != null && !nicknameText.equals("0")) {
            Intent i = new Intent();
            i.setClass(LoginActivity.this, Main2Activity.class);
            startActivity(i);
            app.exit();

        }



    }

    @OnClick(R.id.loginBtns)
    public void onLoginBtnClicked() {
        if(loginName.getText().toString()==null||loginName.getText().toString().equals("")){
            ToastUtil.show(LoginActivity.this,"用户名不能为空");
            return;
        }
        if(password.getText().toString()==null||password.getText().toString().equals("")){
            ToastUtil.show(LoginActivity.this,"密码不能为空");
            return;
        }

        RequestParams params = new RequestParams(Config.LOGIN_URL + "login?__ajax=true");
        params.addBodyParameter("loginName", String.valueOf(loginName.getText()));
        params.addBodyParameter("password", String.valueOf(password.getText()));
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result != null && !result.equals("")) {
                    Gson gson = new Gson();
                    User user = gson.fromJson(result, User.class);

                    if(user.getMessage().equals("nobody")){
                        Toast.makeText(getApplicationContext(), "此用户不存在", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(user.getMessage().equals("false")){
                        Toast.makeText(getApplicationContext(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(user.getMessage().equals("success")){
                        addroleid(user);



                    }
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(), "网络超时错误" + ex, Toast.LENGTH_SHORT).show();
                return;
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });

    }



    private void addroleid(final User user) {
        RequestParams params = new RequestParams(Config.SERVER_URL + "sys/loginapi/getRoleidByUserid");
        params.addBodyParameter("userId", user.getId());
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if(result!=null){
                    app.setAppPreference(user.getLoginName(), user.getName(),user.getId(),user.getSsgrid(),user.getGridname());
                    AppPreferences appPreferences = new AppPreferences(LoginActivity.this);
                    appPreferences.put("role_id",result);
                    getPermissionMenu(user.getId(),user.getName());
//                    addPersonpos(user);
                    Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(LoginActivity.this, Main2Activity.class);
                    startActivity(i);
//                    new PersonposThread(LoginActivity.this).start();
//                    if(!result.equals("73006b03b7f447bf953d065462e5b1ac")){
//                        new NotificationThread(LoginActivity.this).start();
//                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void getPermissionMenu(String userid, String username) {
        RequestParams params = new RequestParams(Config.SERVER_URL + "sys/loginapi/getmenu");
        params.addBodyParameter("userid", userid);
        params.addBodyParameter("username", username);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type listType = new TypeToken<ArrayList<RoleMenu>>() {
                }.getType();
                arrayList = gson.fromJson(result, listType);
                StringBuilder builder = new StringBuilder();
                if (arrayList.size() > 0) {
                    for (int i = 0; i < arrayList.size(); i++) {
                        builder.append(arrayList.get(i).getMenuId());
                        builder.append(",");
                    }
                }
                if (builder.lastIndexOf(",") != -1) {
                    builder.deleteCharAt(builder.lastIndexOf(","));
                }
                permission = builder.toString();
                AppPreferences appPreferences = new AppPreferences(LoginActivity.this);
                appPreferences.put("permission", permission);
//                SharedPreferences.Editor editor = permissionSharedPermission.edit();
//                editor.putString("permission", permission);
//                editor.commit();
                //ToastUtil.show(LoginActivity.this,"permissions--->"+permission);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }





}
